#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2021-06-06 19:45
# @Author  : zym
# @FileName: data_process.py
# @Software: PyCharm
# @Description: 数据处理
import numpy as np
import pandas as pd
import pyecharts.options as opts
from pyecharts.globals import ThemeType
from pyecharts.commons.utils import JsCode
from pyecharts.charts import Timeline, Grid, Bar, Map, Pie


# 正向化矩阵标准化
def l2_normalize(v):
    l2 = np.linalg.norm(v, ord=2, axis=0, keepdims=True)
    return v / l2


# 找每个指标的最大值
def find_max(v):
    return np.amax(v, axis=0)


# 找每个指标的最小值
def find_min(v):
    return np.amin(v, axis=0)


# 计算每个样本对象与最大值的距离
def cal_d_max(z, z_max):
    return (np.sum((z - z_max)**2, axis=1))**0.5


# 计算每个样本对象与最小值的距离
def cal_d_min(z, z_min):
    return (np.sum((z - z_min)**2, axis=1))**0.5


# 计算每个评价对象的得分
def cal_score(d_max, d_min):
    return d_min / (d_max + d_min)


# 将二维数组格式object转换为float64
def o2f(x_object):
    X1 = np.random.rand(x_object.shape[0], x_object.shape[1])  # 创建与x_object同样维度的二维数组
    for i in range(x_object.shape[0]):
        for j in range(x_object.shape[1]):
            if isinstance(x_object[i, j], str):
                X1[i, j] = float(x_object[i, j].replace(' ', ''))
            else:
                X1[i, j] = x_object[i, j]
    return X1


if __name__ == '__main__':
    data = pd.read_csv('data.csv')
    X = np.array(data)
    X = X[:, 1:]  # 去掉地区的列
    X_float = o2f(X)  # 元素类型为np.float64的数组
    Z = l2_normalize(X_float)  # 标准化指标
    z_max = find_max(Z)
    z_min = find_min(Z)
    d_max = cal_d_max(Z, z_max)
    d_min = cal_d_min(Z, z_min)
    score = cal_score(d_max, d_min)
    data['topsis_score'] = score
    area = data['地区']
    dic = {}  # 构造字典, key为地区, value为tuple(对应分数, 分数占分数总和的百分比)
    score_sum = sum(score)
    for i in range(len(score)):
        dic[area[i]] = (score[i], score[i] / score_sum * 100)
